package abba;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.PrintStream;
import java.io.Reader;
import java.io.Writer;
import java.security.InvalidParameterException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;

public class WordsWithSameLetters {

	//sorts the given word lexicographically
	public static String sortLetters(String word)  {
		if (word == null) {
			throw new IllegalArgumentException("Non-existent word!");
		}
		String newWord = "";
		char[] letterArray = word.toCharArray();
		Arrays.sort(letterArray);
		for (int i = 0; i < letterArray.length; i ++) {
			newWord += "" + letterArray[i];
		}
		return newWord;
	}
	
	//reads a file and return ALL words from the file in String array
	public static String [] readFile(String fileName) throws Exception {
		if (fileName == null) 
			throw new InvalidParameterException("Invalid parameter!");
		Scanner scan = null;
		String [] words = null;
		String wholeText = "";
		File file1 = new File(fileName);		
		if (!file1.exists())
			throw new FileNotFoundException("File not found!");
		if (!file1.canRead())
			throw new SecurityException("Cannnot read files!");
		try {
			scan = new Scanner(file1);
			while (scan.hasNext()) {
				wholeText = "" + scan.nextLine();
			}
			words = wholeText.split(" ");
			scan.close();
			return words;			
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			scan.close();
			return words;
		}		
	}
	
	//takes an array of words, finds anagrams,writes them to new file
	public static void writeAnagramsToNewFile(String [] words) throws IOException {
		if (words == null) {
			throw new IllegalArgumentException();
		}
		String sortedWord;
		Writer fw = null;
		BufferedWriter out = null;
		PrintStream stream = new PrintStream(file);
		
		try{
			fw = new FileWriter("Anagrams.txt");
			out = new BufferedWriter(fw);
			
			for (int i = 0; i < words.length-1; i++) {
				sortedWord = sortLetters(words[i]);
				for(int j = i +1; j < words.length; j ++) {
					if (sortedWord.equalsIgnoreCase(sortLetters(words[j]))) {
						out.append(words[i] + " ");
						break;
					}
				}			
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
				try {
				out.close();
				
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}		
	
	public static void main(String[] args)  {
		
		try {
			String [] words = readFile("words.txt");
			writeAnagramsToNewFile(words);
			
		}catch (IOException e) {
			e.printStackTrace();
		}catch (Exception e) {
			e.printStackTrace();
		}
		
	}

}
